package com.elcl.widget.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.elcl.util.viewutils.ViewUtils;

/**
 * @author LCL 2014-11-7 注意：此控件的外层必须是RelativeLayout
 * 1、使用方法 setItems（），将数据放在里面，
 * 已经废弃，替代方案为NumberPicker(官方提供)
 */
public class ABWheelView extends ScrollView {
	// TODO 1、循环选中2、二级或者三级联动3、TextView的重复利用4、输入的类型只能是字符串
	public List<String> items = new ArrayList<String>();
	Context context;
	LinearLayout views;

	int displayItemCount = 5; // 显示的item的数目
	int delayMillis = 50;// 视图刷新的时间段
	int offset = 2;// 偏移量

	int initalY = 0;// 初始的y轴的高度
	Runnable scrollTask;// 滑动的线程
	OnWheelSelectedListener onWheelSelectedListener;
	String[] color = new String[] { "#0288ce", "#bbbbbb", "#83cde6" };

	public interface OnWheelSelectedListener {// 选择后的回调
		void selectedItem(int selectedIndex, String item);
	}

	public ABWheelView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		initialize();
	}

	public ABWheelView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initialize();
	}

	public ABWheelView(Context context) {
		super(context);
		this.context = context;
		initialize();
	}

	private void initialize() {
		views = new LinearLayout(context);
		views.setOrientation(LinearLayout.VERTICAL);
		addView(views);

		initTask();
	}

	int selectedIndex = 1;// 选择的项数（）

	private void initTask() {
		scrollTask = new Runnable() {
			@Override
			public void run() {
				newY = getScrollY();
				if (initalY - newY == 0) {// 滑动停止
					final int divider = newY / itemHeight;
					final int remainder = newY % itemHeight;
					if (remainder == 0) {// 正好滑动在中间位置
						selectedIndex = divider + offset;
					} else {// 不是滑动在中间位置
						if (remainder > itemHeight / 2) {// 如果滑动在大于一半的时候
							selectedIndex = divider + offset + 1;
							smoothScrollTo(0, initalY - remainder + itemHeight);
						} else {
							selectedIndex = divider + offset;
							smoothScrollTo(0, initalY - remainder);
						}
					}
					onSeletedCallBack();
				} else {// 滑动没有停止不断刷新
					initalY = newY;
					postDelayed(scrollTask, delayMillis);
				}
			}
		};
	}

	/**
	 * 选中回调
	 */
	private void onSeletedCallBack() {
		if (null != onWheelSelectedListener) {
			onWheelSelectedListener.selectedItem(selectedIndex - offset,
					items.get(selectedIndex));
		}
	}

	/**
	 * 将list放到TextView中，并将所有的textView放到viewgroup中
	 */
	private void initData() {
		displayItemCount = offset * 2 + 1;
		views.removeAllViews();
		for (String item : items) {
			views.addView(createView(item));
		}
	}

	private int itemHeight = 0;
	private int itempadding = 10;

	/**
	 * 创建相应的textView
	 */
	private View createView(String content) {
		TextView tv_content = new TextView(context);
		tv_content.setLayoutParams(new LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		tv_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
		tv_content.setSingleLine(true);
		tv_content.setGravity(Gravity.CENTER);
		tv_content.setText(content);
		tv_content.setPadding(itempadding, itempadding, itempadding,
				itempadding);

		if (itemHeight == 0) {
			itemHeight = ViewUtils.getViewHeight(tv_content);
			LayoutParams layoutParams = new LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT, itemHeight
							* displayItemCount);
			views.setLayoutParams(layoutParams);
			this.setLayoutParams(new RelativeLayout.LayoutParams(
					layoutParams.width, itemHeight * displayItemCount));// 设置最外层的布局大小为可显示的数目
		}

		return tv_content;
	}

	/**
	 * 刷新itemview字体颜色
	 */
	private void refreshItemView(int y) {
		int position = y / itemHeight + offset;
		int remainder = y % itemHeight;
		int divided = y / itemHeight;// 加这个的原因是防止position的错乱

		if (remainder == 0) {
			position = divided + offset;
		} else {
			if (remainder > itemHeight / 2) {
				position = divided + offset + 1;
			}
		}

		for (int i = 0, len = views.getChildCount(); i < len; i++) {
			TextView itemView = (TextView) views.getChildAt(i);
			if (null == itemView) {
				return;
			}
			if (position == i) {
				itemView.setTextColor(Color.parseColor(color[0]));
			} else {
				itemView.setTextColor(Color.parseColor(color[1]));
			}
		}
	}

	int newY = 0;

	@Override
	public boolean onTouchEvent(MotionEvent ev) {// 这里是解决用力滑动后显示问题和和当你自己滑动到item一半的时候显示问题
		if (ev.getAction() == MotionEvent.ACTION_UP) {
			initalY = getScrollY();
			startScrollTask();
		}
		return super.onTouchEvent(ev);
	}

	private void startScrollTask() {
		this.postDelayed(scrollTask, delayMillis);
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {// 在滑动的过程中改变字体的颜色
		super.onScrollChanged(l, t, oldl, oldt);
		refreshItemView(t);
	}

	@Override
	public void fling(int velocityY) {// 放慢滑动的速度
		super.fling(velocityY / 3);
	}

	public List<String> getItems() {
		return items;
	}

	/**
	 * 最好放在所有属性的后面
	 */
	public void setItems(List<String> list) {
		if (null == items) {
			items = new ArrayList<String>();
		}
		items.clear();
		items.addAll(list);// 将所有的选项加入后，再加空白

		for (int i = 0; i < offset; i++) {// 前后加空白，不然偏移量是1，无法选择首末项
			items.add(0, "");
			items.add("");
		}

		initData();
		refreshItemView(0);
	}

	Paint paint;
	int viewWidth;

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		viewWidth = w;
		setBackgroundDrawable(null);
	}

	@Override
	public void setBackgroundDrawable(Drawable d) {
		if (viewWidth == 0) {
			viewWidth = ((Activity) context).getWindowManager()
					.getDefaultDisplay().getWidth();
		}
		if (null == paint) {
			paint = new Paint();
			paint.setColor(Color.parseColor(color[2]));
			paint.setStrokeWidth(2);
		}
		d = new Drawable() {
			@Override
			public void setColorFilter(ColorFilter cf) {

			}

			@Override
			public void setAlpha(int alpha) {

			}

			@Override
			public int getOpacity() {
				return 0;
			}

			@Override
			public void draw(Canvas canvas) {
				canvas.drawLine(viewWidth * 1 / 6, offset * itemHeight,
						viewWidth * 5 / 6, offset * itemHeight, paint);
				canvas.drawLine(viewWidth * 1 / 6, (offset + 1) * itemHeight,
						viewWidth * 5 / 6, (offset + 1) * itemHeight, paint);
			}
		};

		super.setBackgroundDrawable(d);
	}

	/**
	 * 设置直接跳到哪个位置
	 */
	public void setSelection(final int position) {
		selectedIndex = position + offset;
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				scrollTo(0, position * itemHeight);
			}
		}, 200L);
	}

	public String getSeletedItem() {
		return items.get(selectedIndex);
	}

	public int getSeletedPosition() {// 获得选中的item的位置
		return selectedIndex;
	}

	public int getItempadding() {
		return itempadding;
	}

	/**
	 * 设置每个item的间距
	 */
	public void setItempadding(int itempadding) {
		this.itempadding = itempadding;
	}

	public int getDelayMillis() {
		return delayMillis;
	}

	public void setDelayMillis(int delayMillis) {// 延迟50秒刷新一次
		this.delayMillis = delayMillis;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {// 位置position的偏移量，不让高亮的位置显示在第一位
		this.offset = offset;
	}

	/**
	 * 设置color的值，color[0]是选择字体 颜色，color[1]是没选字体颜色，color[2]是横线的颜色
	 */
	public String[] getColor() {
		return color;
	}

	public void setColor(String[] color) {
		this.color = color;
	}

	/**
	 * 设置可视化的item
	 */
	public int getDiaplayItemCount() {
		return displayItemCount;
	}

	public void setDiaplayItemCount(int displayItemCount) {
		this.displayItemCount = displayItemCount;
	}

	public OnWheelSelectedListener getOnWheelSelectedListener() {
		return onWheelSelectedListener;
	}

	public void setOnWheelSelectedListener(
			OnWheelSelectedListener onWheelSelectedListener) {// 监听回调
		this.onWheelSelectedListener = onWheelSelectedListener;
	}
}
